import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class MyToast {
  static void showToast(BuildContext context,String message){
    show(context, message);
  }
  static void showSystemToast(String message){
    Fluttertoast.showToast(
      msg: message,
      toastLength: Toast.LENGTH_SHORT, // 或 Toast.LENGTH_LONG
      gravity: ToastGravity.CENTER, // TOP / CENTER / BOTTOM
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.black87,
      textColor: Colors.white,
      fontSize: 14.0,
    );
  }



  static void show(
      BuildContext context,
      String message, {
        Duration duration = const Duration(seconds: 2),
      }) {
    // 先移除当前 Overlay 上可能存在的 Toast
    _removeCurrentToast();

    final overlay = Overlay.of(context);
    if (overlay == null) return;

    final overlayEntry = OverlayEntry(
      builder: (ctx) => Positioned(
        // 居中显示
        top: MediaQuery.of(context).size.height / 2 - 50,
        left: MediaQuery.of(context).size.width * 0.1,
        right: MediaQuery.of(context).size.width * 0.1,
        child: _ToastWidget(message: message),
      ),
    );

    _currentEntry = overlayEntry;
    overlay.insert(overlayEntry);

    // 定时移除
    Future.delayed(duration, () {
      _removeCurrentToast();
    });
  }

  static OverlayEntry? _currentEntry;

  static void _removeCurrentToast() {
    _currentEntry?.remove();
    _currentEntry = null;
  }
}

class _ToastWidget extends StatelessWidget {
  final String message;

  const _ToastWidget({required this.message});

  @override
  Widget build(BuildContext context) {
    return Material(
      // 用Material才能有阴影和圆角
      color: Colors.transparent,
      child: Container(
        alignment: Alignment.center,
        width: 100,
        height: 50,

        decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.8),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Text( message,
          style: const TextStyle(color: Colors.white, fontSize: 14),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
}
// ElevatedButton(
// onPressed: () {
// CustomToast.show(context, "这是一个自定义 Toast");
// },
// child: const Text("显示Toast"),
// ),